package com.service;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.stereotype.Service;

@Service
public class MailUtil {

	private static Properties props = new Properties();

	static {
		props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
	}

	public void sendMail(String emailMessage, String destinationEmail,
			final String username, final String password)
			throws MessagingException {

		Session session = Session.getInstance(props,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(username, password);
					}
				});

		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress("svblagodarev@gmail.com"));
		// TODO: add email validation
		message.setRecipients(Message.RecipientType.TO,
				InternetAddress.parse(destinationEmail));
		message.setSubject("Testing Subject");
		message.setText(emailMessage + "\n\n Date: " + new Date());

		Transport.send(message);

		System.out.println("Done");

	}

	public static Properties getProps() {
		return props;
	}

	public static void setProps(Properties props) {
		MailUtil.props = props;
	}

}
